package com.xiaoyu.lanling.data;

import android.content.Context;

import com.xiaoyu.base.app.AppContext;
import com.xiaoyu.lanling.R;
import com.xiaoyu.lanling.widget.picker.area.PickerAreaModel;
import com.xiaoyu.lanling.widget.picker.area.PickerProvinceModel;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import in.srain.cube.app.init.InitializableAsync;
import in.srain.cube.request.JsonData;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;

public class AreaData implements InitializableAsync {

    private static final AreaData INSTANCE = new AreaData();

    private PickerAreaModel mModel;

    public static AreaData getInstance() {
        return INSTANCE;
    }

    private AreaData() {
    }

    @Override
    public void initiateAsync(Context context) {

    }

    public Single<PickerAreaModel> getPickerCityDataModel() {
        return Single.create(emitter -> {
            if (mModel == null || mModel.isInvalid) {
                JsonData jsonData = JsonData.create(tryGetStringFromRaw(emitter));
                mModel = updateAreaFromJsonData(jsonData);
            }
            emitter.onSuccess(mModel);
        });
    }

    private static PickerAreaModel updateAreaFromJsonData(JsonData jsonData) {
        List<JsonData> jsonDataList = jsonData.toList();
        List<PickerProvinceModel> provinceModelList = new ArrayList<>();

        provinceModelList.add((new PickerProvinceModel()));
        for (JsonData provinceRawData : jsonDataList) {
            provinceModelList.add(new PickerProvinceModel(provinceRawData));
        }

        return new PickerAreaModel(provinceModelList);
    }

    private static String tryGetStringFromRaw(SingleEmitter<PickerAreaModel> emitter) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            InputStream inputStream = AppContext.getContext().getResources().openRawResource(R.raw.city);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            inputStream.close();
            bufferedReader.close();
        } catch (Exception e) {
            emitter.onError(e);
        }
        return stringBuilder.toString();
    }
}
